import { Carousel, Divider, Icon, Popover, Tooltip, message } from "antd";
import React from "react"
import { MentionsInput, Mention, SuggestionDataItem } from 'react-mentions';
import { inject, observer, Observer } from 'mobx-react';

import imsdk from '../../net/IMSDK';
import webIM from '../../net/WebIM';

import { imojiData } from '../../config/imojiDataList';
import { SelectItemType, SelectType } from '../../interface/ITransmit';

import './SendBoardSimple.less'
import { ChatStore } from "../../store/ChatStore";
import { MessageItem } from "../../interface/IChat";
import { observerServices } from '../../service/obsService';
import { SystemStore } from "../../store/SystemStore";
import { MessageType } from "../../net/Const";

interface ISendBoardSimpleProps {
  content?:string,
  onContentChange:(msg:MessageItem)=>void
}
interface ISendBoardSimplePropsWithStore extends ISendBoardSimpleProps {
	chatStore: ChatStore;
  systemStore:SystemStore
}
interface ISendBoardSimpleState{
  content:string
  message:MessageItem,
  /**
   * 工具栏
   */
  tools:Array<{
    name:string,
    show?:boolean,
    /**
     * 工具模块的下拉菜单
     */
    options?:any[],
  }>
}

@inject('chatStore','systemStore')
@observer
export default class SendBoardSimple extends React.Component<ISendBoardSimpleProps,ISendBoardSimpleState> {
  constructor(props: ISendBoardSimpleProps) {
    super(props);
    this.state = {
      content:props.content||'',
      tools:[{
        name:'emoji',
        options:[]
      },
      // {
      //   name:'image'
      // }
      ],
      message:{
        type:1,
        chatType:'chat',
        from:'',
        fromUserId:'',
        fromUserName:'',
        content:'',
        to:'',
        toUserId:'',
        toUserName:'',
        id:'',
        jid:'',
        toJid:'',
        messageId:'',
        timeSend:'',
        unreadCount:0
      }
    }
    this.mentionDom = React.createRef()
  }
  componentWillUnmount(): void {
    this.setState({
      content:''
    })
  }
  get injected() {
		return this.props as ISendBoardSimplePropsWithStore;
	}

  getData = async () => {
		const res = await imsdk.getImog();
		if (res && res.resultCode == 1) {
			let defaults = []
			if (res.data) {
				defaults = res.data;
			}
			// console.log('获取的表情数据的长度', defaults.length, "服务端的数据", res)
			if (defaults.length > 0) {
				const emojsList = [{ url: '', name: '' }];
				for (var i = 0; i < defaults.length; i++) {
					if (defaults[i] == null || defaults[i].url == null) {
						continue;
					}
					//    if()
					if (defaults[i].url.length > 1) {
						emojsList[i] = {
							url: defaults[i].url ? defaults[i].url : '',
							name: defaults[i].url ? defaults[i].emojiId : '',
						};
					}

				}
        
				this.setState({
          tools:this.state.tools.map((item)=>{
            if(item.name == 'emoji'){
              item.options = emojsList
            }
            return item
          })
        })
			} else {
				this.setState({
					tools:this.state.tools.map((item)=>{
            if(item.name == 'emoji'){
              item.options = []
            }
            return item
          })
				})
			}

		}
		
	}
  componentDidMount(): void {
      this.getData();
  }
  currentMessageItem:MessageItem = {
    type:1,
    chatType:'chat',
    from:'',
    fromUserId:'',
    fromUserName:'',
    content:'',
    to:'',
    toUserId:'',
    toUserName:'',
    id:'',
    jid:'',
    toJid:'',
    messageId:'',
    timeSend:'',
    unreadCount:0
  }
  toolsRefs = {}
  mentionDom = null
  defaultStyles={
		control: {
			//backgroundColor: '#FBFCFE',

			fontSize: 14,
			fontWeight: 'normal'
		},

		highlighter: {
			overflow: 'hidden'
		},

		input: {
			margin: 0,
			overflow: 'auto',
			maxHeight: 400
		},

		'&singleLine': {
			control: {
				display: 'inline-block',

				width: 130
			},

			highlighter: {
				padding: 1,
				border: '2px inset transparent'
			},

			input: {
				padding: 1,

				border: '2px inset'
			}
		},

		'&multiLine': {
			control: {},

			highlighter: {},

			input: {
				outline: 0,
				border: 0
			}
		},

		suggestions: {
			list: {
				backgroundColor: '#f5f5f5',
				boxShaow: '1px 1px 4px #cac7c7',
				fontSize: 14,
				maxHeight: 160,
				overflow: 'auto',
				position: 'absolute',
				bottom: 14,
				zIndex: 99999
			},

			item: {
				padding: '4px 12px',
				'&focused': {
					backgroundColor: '#D0E6FD'
				}
			}
		}
  }
  changeContent = (e:any) => {
    this.setState({
      content:e.target.value
    })
    this.currentMessageItem.content = e.target.value = e.target.value;
    this.props.onContentChange(this.currentMessageItem)
  }
  textAreaKeyDown = (e:any) => {
    
  }
  handleDrageOver = (e:any) => {
    e.preventDefault();
  }
  handleFileDrop = (e:any) => {
    
  }
  getPlaceholder = () => {
    return "输入消息内容"
  }
  getName = (name: string) => {
		return `@${name} `;
	};
  usersList: { id: string; display: string }[];
  renderSuggestion = (props:any) => {
    return null
  }
  onAdd = (mention:any) => {
    
  }
  mentionStyle = {
    
  }
  renderToolEmoji = () => {
    const config = this.state.tools.find((item)=>{
      return item.name == 'emoji'
    }) || {options:[],show:false}

    const imogiList = (
      <div className="imoglist" key={1}>
        <Carousel dots={false} ref={(el) => {
          this.toolsRefs['emoji'] = el;
        }}>
          <div className="imojiPanel">
            {imojiData.map((imoji, index) => {
              return (
                <img
                  key={index}
                  src={imoji.img}
                  alt="imoji"
                  onClick={() => {
                    const code = imoji.english
                    let content = this.state.content + '[' + code + ']';
                    this.currentMessageItem.content = content;
                    this.setState({
                      content,
                    },()=>{
                      this.props.onContentChange(this.currentMessageItem)
                    });
                  }}
                />
              );
            })}
          </div>
          
        </Carousel>
        <Divider className="divider" />
        <Icon
          type="smile"
          theme="filled"
          style={{ color: '#FFC61E', fontSize: '18px', margin: '5px 10px' }}
          onClick={()=>{
            if( this.toolsRefs['emoji']){
              this.toolsRefs['emoji'].prev();
            }
          }}
        />
        <Icon
          type="heart"
          theme="filled"
          style={{ color: '#E94F4F', fontSize: '18px', margin: '5px 10px' }}
          onClick={()=>{
            if( this.toolsRefs['emoji']){
              this.toolsRefs['emoji'].next();
            }
          }}
        />
      </div>
    );

    return <div className="toolkit-icon">
      <Popover
          content={imogiList}
          title=""
          placement="topLeft"
          trigger="click"
          visible={config.show}
          onVisibleChange={(visible)=>{
            this.setState({
              tools:this.state.tools.map((item)=>{
                if(item.name == 'emoji'){
                  item.show = visible
                }
                return item
              })
            })
          }}
        >
          <span className={this.isElectron() ? "emoji-item" : "emoji-item-web"} onClick={()=>{
            this.setState({
              tools:this.state.tools.map((item)=>{
                if(item.name == 'emoji'){
                  item.show = !item.show
                }
                return item
              })
            })
          }}>
            <span className='icon icon-emoji'></span>
          </span>
      </Popover>
      </div>
  }
  renderToolImage = () => {
    return <div className="toolkit-icon">
      <Tooltip title="传图片">
        <label className="item" onClick={()=>{

        }}>
        {/* <IconImgEdit img={require('../../assets/image/image-blue-icon.png')} size={20} classN="send-item" /> */}
        <span className="icon icon-image-upload"></span>
        <input
          type="file"
          ref={(ref) =>{
            this.toolsRefs['image'] = ref;
          }}
          accept="image/png,image/jpeg,image/gif"
          style={{ display: 'none' }}
          onChange={async (e) => {
            const chatStore = this.injected.chatStore;
            const systemStore = this.injected.systemStore
            const currentChatId = chatStore.currentChatData.id
            if (e.target.files && e.target.files.length > 0) {
              const fileImg = e.target.files[0];
              this.currentMessageItem = webIM.createMessage(2, ' ', currentChatId, chatStore.currentChatData.name);
              let reader = new FileReader();
              reader.readAsDataURL(fileImg);
              reader.onload = (evt: any) => {
                if (evt) {
                  var image = new Image();
                  image.onload = (e: any) => {
                    this.currentMessageItem.location_x = String(image.width);
                    this.currentMessageItem.location_y = String(image.height);
                    // console.log('上传的数据',e.target.result,e)
                  };
                  image.src = evt.target.result;
                  this.currentMessageItem.content = evt.target.result;
        
                  chatStore.addMessage(currentChatId, this.currentMessageItem, true);
                }
              };
              let imgUrl = await observerServices.uploadFile(fileImg, systemStore.uploadUrl);
              this.fileUploadComplete(imgUrl, currentChatId);
              // this.imgMsg = _imgMsg;
              // // console.log('图片上传obs', imgUrl);
              // this.uploadComplete(imgUrl, currentChatId, _imgMsg);
            }
          }}
        /></label>
      </Tooltip>
    </div>
  }
  fileUploadComplete = (url: string, id: string) => {
		if (!url) {
			return;
		}
		this.currentMessageItem.content = url;
		//this.injected.chatStore.updtateContent(this.currentMessageItem);
		//webIM.sendMessage(this.currentMessageItem, id);
		// console.log('上传成功', url);
	};
  isElectron(){
    return global['electron'];
  }
  send = (_chat: any) => {
    var content = this.currentMessageItem.content;
    const chatStore = this.injected.chatStore
    if (!content) {
      message.warn('不能发送空内容');
      return;
    }
    let chat = _chat.data;
    let chatId = "";
    let toUserName = "";
    if (_chat.transmitType == SelectType.chat) {
      chatId = chat.id + '';
      toUserName = chat.name;

    } else if (_chat.transmitType == SelectType.group) {
      chatId = chat.jid + '';
      toUserName = chat.name;
    } else if (_chat.transmitType == SelectType.friend) {
      chatId = chat.toUserId + '';
      toUserName = chat.toNickname;
    }
    console.log(chatId, '-----chatId--------');


    // let chart = chatStore;
    // const chatItem = chart.chats.find(item => item.id == chatId);
    // console.log('发送的消息', chatItem);
    const _msgData = {
      type: MessageType.TEXT,
      content: content,
      toUserId: chatId,
      toUserName: toUserName
    };

    
    const msg = webIM.createMessage(_msgData.type, _msgData.content, _msgData.toUserId, _msgData.toUserName);

    
    return;
    webIM.sendMessage(msg, '');

    // console.log(msg,'发出的消息是什么?????????????',msg.to,msg.toJid,msg.toUserId,msg.toUserName)
    // msg.fromUserName = chart.currentChatData.nickname ? chart.currentChatData.nickname : msg.fromUserName;
    chatStore.addMessage(chatId, msg, true);
    // console.log(this.injected.chatStore.messageData.get(chatId),'消息体里的数据') 
    chatStore.updateMes(content, msg.timeSend, chatId);
    //chatStore.addToChats(chat);
  };

  getUsersList = () => {
  	
  }
  
  sendToChats = (chats: SelectItemType[]) => {
    for (let index = 0; index < chats.length; index++) {
      const chat = chats[index];

      let timer = setInterval(() => {
        timer && clearTimeout(timer);
        this.send(chat)
      }, 50);

    }
    
  };
  render(){
    return <>
      <div className="sendboard-simple">
        <div className='sendboard-simple-input-wrapper'>
        <MentionsInput
          className="sendboard-simple-input"
          value={this.state.content}
          onChange={this.changeContent}
          onKeyDown={this.textAreaKeyDown}
          onDragOver={this.handleDrageOver}
          onDrop={this.handleFileDrop}
          style={this.defaultStyles}
          inputRef={this.mentionDom}
          placeholder={this.getPlaceholder()}
        // autoFocus={chatStore.isReply?true:false}
        >
          <Mention
            className="sendboard-simple-mention"
            trigger="@"
            markup="@__display__ "
            displayTransform={this.getName}
            data={this.usersList}
            // suggestions={['afc163', 'benjycui', 'yiminghe', 'jljsj33', 'dqaria', 'RaoHai']}
            renderSuggestion={this.renderSuggestion}
            onAdd={this.onAdd}
            style={this.mentionStyle}
          />
        </MentionsInput>
        </div>
        <div className="send-toolkit">
					<div className="toolkit-left">
            {
              this.state.tools.map((item,index)=>{
                if(item.name == 'emoji'){
                  return this.renderToolEmoji()
                }else if(item.name=='image'){
                  return this.renderToolImage();
                }
                return null
              })
            }
						
					</div>
					
				</div>
        
      </div>
    </>
  }
}
